<template>
    <div class="address-book-container">
        <div class="page-header">
            <h2>地址管理</h2>
            <div>
                <el-button @click="fetchAddressList" icon="Refresh" style="margin-right: 10px;">刷新</el-button>
                <el-button type="primary" @click="handleAddAddress">新增地址</el-button>
            </div>
        </div>

        <!-- 调试信息 -->
        <div class="debug-info" v-if="showDebugInfo">
            <h3>调试信息</h3>
            <pre>{{ JSON.stringify(addressList, null, 2) }}</pre>
            <el-button size="small" @click="showDebugInfo = false">隐藏调试信息</el-button>
        </div>
        <el-button v-else size="small" @click="showDebugInfo = true" style="margin-bottom: 10px;">显示调试信息</el-button>

        <div class="address-list" v-loading="loading">
            <el-empty description="暂无地址信息" v-if="addressList.length === 0"></el-empty>

            <el-card v-for="item in addressList" :key="item.id" class="address-card">
                <div class="address-info">
                    <div class="address-header">
                        <span class="consignee">{{ item.consignee }}</span>
                        <span class="phone">{{ item.phone }}</span>
                        <el-tag type="success" v-if="item.isDefault === 1" size="small">默认</el-tag>
                    </div>
                    <div class="address-detail">
                        <div v-if="item.provinceName || item.cityName || item.districtName">
                            {{ item.provinceName || '' }} {{ item.cityName || '' }} {{ item.districtName || '' }}
                        </div>
                        {{ item.detail }}
                    </div>
                    <div v-if="item.label" class="address-label">
                        <el-tag size="small" type="info">{{ item.label }}</el-tag>
                    </div>
                </div>
                <div class="address-actions">
                    <el-button type="text" @click="handleEditAddress(item)">编辑</el-button>
                    <el-button type="text" @click="handleSetDefault(item)" v-if="item.isDefault !== 1">设为默认</el-button>
                    <el-button type="text" @click="handleDeleteAddress(item)" class="delete-btn">删除</el-button>
                </div>
            </el-card>
        </div>

        <!-- 地址编辑对话框 -->
        <el-dialog :title="dialogTitle" v-model="dialogVisible" width="500px" @closed="resetForm">
            <el-form :model="addressForm" :rules="rules" ref="addressFormRef" label-width="80px">
                <el-form-item label="收货人" prop="consignee">
                    <el-input v-model="addressForm.consignee" placeholder="请输入收货人姓名"></el-input>
                </el-form-item>
                <el-form-item label="手机号" prop="phone">
                    <el-input v-model="addressForm.phone" placeholder="请输入手机号"></el-input>
                </el-form-item>
                <el-form-item label="详细地址" prop="detail">
                    <el-input v-model="addressForm.detail" type="textarea" rows="3" placeholder="请输入详细地址信息"></el-input>
                </el-form-item>
                <el-form-item label="标签" prop="label">
                    <el-input v-model="addressForm.label" placeholder="如：家、公司、学校等"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-checkbox v-model="addressForm.isDefaultChecked">设为默认地址</el-checkbox>
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="submitForm" :loading="submitLoading">确认</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getAddressList, addAddress, updateAddress, setDefaultAddress, deleteAddress, getAddressById } from '@/api/address'

const loading = ref(false)
const addressList = ref([])
const dialogVisible = ref(false)
const addressFormRef = ref(null)
const submitLoading = ref(false)
const isEdit = ref(false)
const showDebugInfo = ref(false)

const addressForm = reactive({
    id: null,
    userId: null,
    consignee: '',
    phone: '',
    detail: '',
    label: '',
    isDefault: 0,
    isDefaultChecked: false
})

const dialogTitle = computed(() => isEdit.value ? '修改地址' : '新增地址')

const rules = {
    consignee: [
        { required: true, message: '请输入收货人姓名', trigger: 'blur' }
    ],
    phone: [
        { required: true, message: '请输入手机号', trigger: 'blur' },
        { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
    ],
    detail: [
        { required: true, message: '请输入详细地址', trigger: 'blur' }
    ]
}

// 获取地址列表
const fetchAddressList = async () => {
    loading.value = true
    try {
        console.log('开始获取地址列表...')
        const res = await getAddressList()
        console.log('获取到的地址列表数据:', res)

        // 确保地址列表是数组
        if (Array.isArray(res)) {
            addressList.value = res
        } else if (res && Array.isArray(res.data)) {
            addressList.value = res.data
        } else {
            console.warn('返回的地址数据不是数组格式:', res)
            addressList.value = []
        }

        console.log('处理后的地址列表:', addressList.value)
    } catch (error) {
        console.error('获取地址列表失败', error)
        ElMessage.error('获取地址列表失败，请稍后再试')
        addressList.value = []
    } finally {
        loading.value = false
    }
}

// 新增地址按钮
const handleAddAddress = () => {
    isEdit.value = false
    resetForm()
    dialogVisible.value = true
}

// 编辑地址
const handleEditAddress = (address) => {
    isEdit.value = true
    Object.keys(addressForm).forEach(key => {
        if (key !== 'isDefaultChecked') {
            addressForm[key] = address[key]
        }
    })
    addressForm.isDefaultChecked = address.isDefault === 1
    dialogVisible.value = true
}

// 设为默认地址
const handleSetDefault = async (address) => {
    try {
        await setDefaultAddress({ id: address.id })
        ElMessage.success('默认地址设置成功')
        fetchAddressList()
    } catch (error) {
        console.error('设置默认地址失败', error)
        ElMessage.error('设置默认地址失败，请稍后再试')
    }
}

// 删除地址
const handleDeleteAddress = (address) => {
    ElMessageBox.confirm(
        '确定要删除该地址吗？',
        '提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }
    ).then(async () => {
        try {
            await deleteAddress(address.id)
            ElMessage.success('删除成功')
            fetchAddressList()
        } catch (error) {
            console.error('删除地址失败', error)
            ElMessage.error('删除地址失败，请稍后再试')
        }
    }).catch(() => { })
}

// 提交表单
const submitForm = () => {
    addressFormRef.value.validate(async (valid) => {
        if (valid) {
            submitLoading.value = true
            try {
                console.log('提交地址表单:', addressForm)

                // 构建处理好的表单数据
                const formData = {
                    id: addressForm.id,
                    consignee: addressForm.consignee,
                    phone: addressForm.phone,
                    detail: addressForm.detail,
                    label: addressForm.label,
                    isDefault: addressForm.isDefaultChecked ? 1 : 0
                }

                console.log('提交给API的数据:', formData)

                if (isEdit.value) {
                    await updateAddress(formData)
                    ElMessage.success('修改地址成功')
                } else {
                    await addAddress(formData)
                    ElMessage.success('新增地址成功')
                }
                dialogVisible.value = false
                fetchAddressList()
            } catch (error) {
                console.error(`${isEdit.value ? '修改' : '新增'}地址失败`, error)
                ElMessage.error(`${isEdit.value ? '修改' : '新增'}地址失败，请稍后再试`)
            } finally {
                submitLoading.value = false
            }
        }
    })
}

// 重置表单
const resetForm = () => {
    if (addressFormRef.value) {
        addressFormRef.value.resetFields()
    }
    Object.assign(addressForm, {
        id: null,
        userId: null,
        consignee: '',
        phone: '',
        detail: '',
        label: '',
        isDefault: 0,
        isDefaultChecked: false
    })
}

onMounted(() => {
    fetchAddressList()
})
</script>

<style scoped>
.address-book-container {
    padding: 20px;
}

.page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
}

.address-list {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
    gap: 20px;
}

.address-card {
    display: flex;
    flex-direction: column;
    height: 100%;
}

.address-info {
    flex: 1;
    margin-bottom: 15px;
}

.address-header {
    display: flex;
    align-items: center;
    margin-bottom: 10px;
}

.consignee {
    font-weight: bold;
    margin-right: 10px;
}

.phone {
    color: #666;
    margin-right: 10px;
}

.address-detail {
    color: #333;
    line-height: 1.5;
}

.address-actions {
    display: flex;
    justify-content: flex-end;
    border-top: 1px solid #eee;
    padding-top: 10px;
}

.address-label {
    margin-top: 5px;
}

.delete-btn {
    color: #F56C6C;
}
</style>